package edu.wata.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.wata.db.utils.JdbcTemplate;

import edu.wata.dao.iface.ArticleDao;
import edu.wata.domain.Article;

public class ArticleJdbcDaoImpl implements ArticleDao {

	@Override
	public List<Article> getArticleByType(int typeId) {
		String sql = "select * from Article where typeId=?";
		List<Article> list = JdbcTemplate.query(sql, (rs) -> {
			List<Article> list0 = new ArrayList<>();
			try {
				while (rs.next()) {
					Article article = new Article(rs.getInt(1), rs.getString(2), rs.getString(3),
							rs.getDate(4).toLocalDate(), rs.getInt(5), rs.getInt(6), rs.getInt(7), rs.getInt(8),
							rs.getInt(9), rs.getInt(10));
					list0.add(article);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			return list0;
		}, new Object[] { typeId });
		return list;
	}

	@Override
	public List<Map<String, Object>> getArticleMapByType(int typeId) {
		String sql = "select a.id,a.title,to_char(a.content) content,a.publishtime,a.click,a.likenumber,at1.typename subname,at2.typename parentname,u.name username,a.top,a.support"
				+ " from Article a left outer join ArticleType at1 on a.typeId=at1.id"
				+ " left outer join ArticleType at2 on at1.parentId=at2.id"
				+ " left outer join users u on a.userid=u.id where typeId=?";
		List<Map<String, Object>> list = JdbcTemplate.query(sql, (rs) -> {
			List<Map<String, Object>> list0 = new ArrayList<>();
			try {
				while (rs.next()) {
					Map<String, Object> map = new HashMap<>();
					for (int i = 0, len = rs.getMetaData().getColumnCount(); i < len; i++) {
						map.put(rs.getMetaData().getColumnName(i + 1), rs.getObject(i + 1));
					}
					list0.add(map);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			return list0;
		}, new Object[] { typeId });
		return list;
	}

}
